<template>
  <div style="margin: 30px 0 0 20px; width: 364px">
    <Person :personList="roomData.players" @update="emit('getRoomInfo')" />
    <el-form
      :model="form"
      label-width="auto"
      style="max-width: 1000px; margin-top: 40px"
      :rules="rules"
      ref="ruleFormRef"
    >
      <el-form-item>
        <div style="padding-left: 0px">
          <div style="margin-bottom: 30px">
            <div class="button_box">
              <el-button type="primary" @click="toStartgame">开始游戏</el-button>
              <el-button type="primary" @click="upLoadCard">用户发牌</el-button>
              <el-button type="primary" @click="openCards(4)">翻开3张牌</el-button>
            </div>
            <div class="button_box">
              <el-button type="primary" @click="openCards(5)">翻开第4张</el-button>
              <el-button type="primary" @click="openCards(6)">翻开第5张</el-button>
              <el-button type="danger" @click="toEndgame(false)">结束游戏</el-button>
            </div>
          </div>
          <el-button type="primary" v-if="!isJoin" @click="joinChannel('host')">开启直播</el-button>
          <el-button type="danger" v-if="!isJoin" @click="toEndgame(true)">强制结束游戏</el-button>
          <el-button type="danger" v-if="!isJoin" @click="toEquipmentImport(true)">设备录入</el-button>
          <!-- <el-button type="primary" v-if="!isJoin" @click="joinChannel('audience')">加入</el-button> -->
          <template v-if="isJoin">
            <!-- <el-button :type="hasVideo ? 'danger' : 'primary'" icon="Microphone" v-if="roleType == 'host'"
            >{{ hasVideo ? "关闭" : "开启" }}摄像头</el-button
            >
            <el-button :type="hasVideo ? 'danger' : 'primary'" icon="VideoCamera" v-if="roleType == 'host'"
            >{{ hasAudio ? "关闭" : "开启" }}麦克风</el-button
            > -->
            <el-button @click="emit('leaveChannel')" type="danger">结束直播</el-button>
          </template>
        </div>
      </el-form-item>
    </el-form>
    <EquipmentDailog v-if="equipmentVisibale" v-model:visible="equipmentVisibale" />
  </div>
</template>
<script setup>
import { reactive, ref, computed } from "vue";
import Cookies from "js-cookie";
import AgoraRTC from "agora-rtc-sdk-ng";
import Person from "./person.vue";
import { ElLoading, ElMessage, ElMessageBox } from "element-plus";
import { gameStart, agoraToken, gameSettle, upload4Test, roundNext } from "@/js/api.js";
import EquipmentDailog from "./equipmentDailog.vue";

const token = Cookies.get("authToken");

const form = reactive({
  channel: "",
  uid: "",
});
const ruleFormRef = ref(null);
const roleType = ref("");

const props = defineProps({
  isJoin: {
    type: Boolean,
    default: false,
  },
  localUser: {
    type: Object,
    default: () => ({}),
  },
  roomData: {
    type: Object,
    default: () => ({}),
  },
});
const emit = defineEmits(["leaveChannel", "joinStart", "getRoomInfo"]);

const rules = reactive({
  channel: [{ required: true, message: "请输入房间号", trigger: "blur" }],
  uid: [{ required: true, message: "请输入用户名", trigger: "blur" }],
});
const playStep = ref(1); // 1：开始游戏，2：读取卡牌，3：翻开3张公共牌，4：翻开1张公共牌，5：翻开1张公共牌，6：游戏结束
const equipmentVisibale = ref(false);
let hasVideo = computed(() => {
  return !!props.localUser.videoTrack || false;
});

let hasAudio = computed(() => {
  return !!props.localUser.audioTrack || false;
});

const toEquipmentImport = () => {
  equipmentVisibale.value = true;
};
// 读取卡牌
const upLoadCard = () => {
  upload4Test().then((res) => {
    if (res.code == 200) {
      playStep.value = 3;
      ElMessage.success("读取卡牌成功");
    }
  });
};
// 开始游戏
const toStartgame = async () => {
  let isStart = false;
  try {
    isStart = await ElMessageBox.confirm("是否确认开始游戏?", "提示", {
      confirmButtonText: "开始",
      cancelButtonText: "取消",
      type: "warning",
    });
  } catch {
    isStart = false;
  }
  if (!isStart) return;
  gameStart().then((res) => {
    if (res.code == 200) {
      playStep.value = 2;
      ElMessage.success("游戏已开始");
    }
  });
};
// 翻牌
const openCards = (next) => {
  roundNext().then((res) => {
    if (res.code == 200) {
      playStep.value = next;
      ElMessage.success("翻牌成功");
    }
  });
};

// 结束游戏
const toEndgame = async (bol = false) => {
  let isSure = false;
  if (bol) {
    try {
      isSure = await ElMessageBox.confirm("是否强制结束游戏?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
    } catch {
      isSure = false;
    }
  }
  if (!isSure && bol) return;
  gameSettle({ force: bol }).then((res) => {
    if (res.code == 200) {
      playStep.value = 1;
      ElMessage.success("游戏已结束");
      emit("getRoomInfo");
    }
  });
};
const joinChannel = async (val) => {
  // await ruleFormRef.value.validate();
  let cameras;
  try {
    cameras = await AgoraRTC.getCameras();
  } catch (e) {
    cameras = e;
  }
  if (cameras?.length > 0) {
  } else
    return ElMessageBox.alert("未获取到摄像头，请检查设备或权限！", "提示", {
      confirmButtonText: "确定",
      type: "warning",
    });

  agoraToken().then((res) => {
    if (res.code == 200) {
      emit("joinStart", { ...res.data, role: val });
    }
  });
  roleType.value = val;
};
</script>
<style scoped lang="less">
.button_box {
  :deep(.el-button) {
    width: 88px;
  }
}
</style>
